package exia.java.core.services;

import net.sf.hibernate.*;
import net.sf.hibernate.cfg.*;

/**
 * 
 * @author Jeannette Sebastien
 *
 */
class HibernateUtil {
	
	private static SessionFactory sessionFactory;
	private static final ThreadLocal session = new ThreadLocal();
	
	/**
	 * 
	 * @return
	 */
	public static SessionFactory getSessionFactory()throws HibernateException{
		if(sessionFactory == null){
			sessionFactory = new Configuration().configure().buildSessionFactory();
		}
		return sessionFactory;
	}
	
	/**
	 * 
	 * @return
	 * @throws HibernateException
	 */
	public static Session createSession()throws HibernateException{
		Session s = (Session) session.get();
		if(s == null){
			s = getSessionFactory().openSession();
			session.set(s);
		}
		return s;
	}
	
	/**
	 * 
	 * @throws HibernateException
	 */
	public static void closeSession()throws HibernateException{
		Session s = (Session) session.get();
		session.set(null);
		if(s != null){
			s.close();
		}
	}
}
